<template>
  <div class="container">
    <template>
      <el-tabs v-model="activeName">
        <!-- 角色管理模块 -->
        <el-tab-pane :label="$t('companySetting.roleManagement')" name="first">
          <el-button type="primary" @click="openAddVisible">
            {{ $t("companySetting.addRole") }}
          </el-button>
          <!-- 中间表格部分 -->
          <custom-table
            :data="rolesList.rows"
            :columns="columns"
            :total="rolesList.total"
            :current-page.sync="currentPage"
            :page-size.sync="pageSize"
            :table-props="{
              border: true,
            }"
            @update:currentPage="onPageChange"
            @update:pageSize="onPageSizeChange"
          >
            <template v-slot="{ row }">
              <el-button size="mini" @click="openPermissionVisible(row.id)">
                {{ $t("companySetting.assignPermissions") }}
              </el-button>
              <el-button
                type="primary"
                size="mini"
                @click="openEditVisible(row)"
              >
                {{ $t("companySetting.edit") }}
              </el-button>
              <el-button size="mini" type="danger" @click="onDelete(row.id)">
                {{ $t("companySetting.delete") }}
              </el-button>
            </template>
          </custom-table>
          <!-- 中间表格部分 -->
          <!-- <el-table
            :data="rolesList.rows"
            style="width: 100%"
            :row-class-name="getRowClassName"
          >
            <el-table-column
              width="180"
              type="index"
              :index="1"
              :label="$t('companySetting.serialNumber')"
            >
            </el-table-column>
            <el-table-column
              prop="name"
              width="180"
              :label="$t('companySetting.role')"
            >
            </el-table-column>
            <el-table-column
              prop="description"
              :label="$t('companySetting.description')"
            ></el-table-column>
            <el-table-column
              fixed="right"
              :label="$t('companySetting.operation')"
              width="320"
            >
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="primary"
                  @click="openPermissionVisible(scope.row.id)"
                >
                  {{ $t("companySetting.assignPermissions") }}
                </el-button>
                <el-button
                  @click="openEditVisible(scope.row)"
                  size="small"
                  type="primary"
                >
                  {{ $t("companySetting.edit") }}
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="onDelete(scope.row.id)"
                >
                  {{ $t("companySetting.delete") }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            layout="prev, pager, next"
            :total="rolesList.total"
            :page-size="10"
            @current-change="onPageChange"
          >
          </el-pagination> -->
          <!-- 编辑对话框 -->
          <el-dialog
            :title="$t('companySetting.editRole')"
            :visible.sync="editVisible"
          >
            <el-form :model="editForm" :rules="addRules">
              <el-form-item
                :label="$t('companySetting.roleName')"
                :label-width="formLabelidth"
                prop="name"
              >
                <el-input v-model="editForm.name" autocomplete="off" />
              </el-form-item>
              <el-form-item
                :label="$t('companySetting.roleDescription')"
                :label-width="formLabelidth"
                prop="desc"
              >
                <el-input v-model="editForm.desc" autocomplete="off" />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="editVisible = false">
                {{ $t("companySetting.cancel") }}
              </el-button>
              <el-button type="primary" @click="onEdit">
                {{ $t("companySetting.determine") }}</el-button>
            </div>
          </el-dialog>
          <!-- 新增对话框 -->
          <el-dialog
            :title="$t('companySetting.addRole')"
            :visible.sync="addVisible"
            destroy-on-close
          >
            <el-form :model="addForm" :rules="addRules">
              <el-form-item
                class="role-name"
                :label="$t('companySetting.roleName')"
                :label-width="formLabelidth"
                prop="name"
              >
                <el-input v-model="addForm.name" autocomplete="off" />
              </el-form-item>
              <el-form-item
                :label="$t('companySetting.roleDescription')"
                :label-width="formLabelidth"
                prop="desc"
              >
                <el-input v-model="addForm.desc" autocomplete="off" />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="addVisible = false">
                {{ $t("companySetting.cancel") }}
              </el-button>
              <el-button type="primary" @click="onAdd">
                {{ $t("companySetting.determine") }}
              </el-button>
            </div>
          </el-dialog>
        </el-tab-pane>
        <!-- 公司信息模块 -->
        <el-tab-pane
          :label="$t('companySetting.companyInformation')"
          name="second"
        >
          <el-alert
            :title="$t('companySetting.companyTip')"
            type="info"
            show-icon
            :closable="false"
          />
          <div style="margin: 30px" />
          <!-- 公司信息表格部分 -->
          <el-form
            :label-position="labelPosition"
            label-width="80px"
            :model="formLabelAlign"
            :disabled="true"
          >
            <el-form-item
              :label="$t('companySetting.companyName')"
              :label-width="formCompanyLabelWidth"
            >
              <el-input v-model="formLabelAlign.companyName" />
            </el-form-item>
            <el-form-item
              :label="$t('companySetting.companyAddress')"
              :label-width="formCompanyLabelWidth"
            >
              <el-input v-model="formLabelAlign.companyAddress" />
            </el-form-item>
            <el-form-item
              :label="$t('companySetting.companyEmail')"
              :label-width="formCompanyLabelWidth"
            >
              <el-input v-model="formLabelAlign.companyEmail" />
            </el-form-item>
            <el-form-item
              :label="$t('companySetting.remarks')"
              :label-width="formCompanyLabelWidth"
            >
              <el-input
                v-model="formLabelAlign.remarks"
                type="textarea"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!--分配权限对话框 -->
        <el-dialog
          :title="$t('companySetting.assignPermissions')"
          :visible.sync="permissionVisible"
          destroy-on-close
        >
          <i v-if="permissionLoading" class="el-icon-loading" />
          <el-tree
            v-else
            ref="tree"
            :data="permissionList"
            show-checkbox
            default-expand-all
            node-key="id"
            check-strictly
            :default-checked-keys="oneRole"
            :props="{ children: 'children', label: 'name' }"
          />
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="assignPermission">
              {{ $t("companySetting.determine") }}
            </el-button>
            <el-button @click="closePermissionDialog">
              {{ $t("companySetting.cancel") }}
            </el-button>
          </div>
        </el-dialog>
      </el-tabs>
    </template>
    <el-button @click="exportExcel">导出excel</el-button>
  </div>
</template>
<script>
// 正在编辑的id
let editingId = -1
function getCheckFunc(field) {
  return function(rule, value, callback) {
    if (!value) {
      callback(new Error(this.$t('companySetting.dialogTip.add.' + field)))
    } else {
      callback()
    }
  }
}
import { mapState, mapActions } from 'vuex'
import * as companySetting from '@/api/company-setting'
import ExcelJS from 'exceljs'
import FileSaver from 'file-saver'
export default {
  data() {
    return {
      // 标签栏切换
      activeName: 'first',
      labelPosition: 'right',
      formCompanyLabelWidth: '140px',
      formLabelAlign: {
        companyName: this.$t('companySetting.formLabelAlign.companyName'),
        companyAddress: this.$t('companySetting.formLabelAlign.companyAddress'),
        companyEmail: this.$t('companySetting.formLabelAlign.companyEmail'),
        remarks: this.$t('companySetting.formLabelAlign.remarks')
      },
      // 编辑/新增的验证规则
      addRules: {
        name: [
          {
            required: true,
            trigger: 'change',
            validator: getCheckFunc('name').bind(this)
          }
        ],
        desc: [
          {
            required: true,
            trigger: 'change',
            validator: getCheckFunc('desc').bind(this)
          }
        ]
      },
      // 是否显示分配权限对话框
      permissionVisible: false,
      // 分配权限是否加载中
      permissionLoading: false,
      // 编辑对话框是否显示
      editVisible: false,
      // 新增对话框是否显示
      addVisible: false,
      addForm: {
        name: '',
        desc: ''
      },
      editForm: {
        name: '',
        desc: ''
      },
      formLabelidth: '140px',
      // 表格组件传参
      currentPage: 1,
      pageSize: 10,
      // 表格组件传参
      columns: [
        {
          label: '序号',
          // 没有prop的时候 显示索引
          width: 200
        },
        {
          label: '角色',
          prop: 'name'
        },
        {
          label: '描述',
          prop: 'description'
        },
        {
          label: '操作',
          prop: 'op', // 暂时没用的
          needSlot: true
        }
      ]
    }
  },
  watch: {
    currentPage(n) {
      console.log(n)
    }
  },
  computed: {
    ...mapState('company-setting', ['rolesList', 'oneRole', 'permissionList'])
  },
  methods: {
    ...mapActions('company-setting', [
      'updateRolesList',
      'updateOneRole',
      'updatePermissionList'
    ]),
    // 动态生成表格样式
    getRowClassName(rowInfo) {
      const colorList = ['red', 'green', 'yellow']
      const idx = rowInfo.rowIndex % colorList.length
      return colorList[idx]
      // if (rowInfo.rowIndex % 2 === 1) {
      //   return 'red';
      // }
      // return '';
    },
    // 分页切换
    onPageChange(currentPage) {
      this.updateRolesList({
        page: currentPage,
        pagesize: this.pageSize
      })
    },
    // 分页条数切换
    onPageSizeChange(pageSize) {
      this.updateRolesList({
        page: 1,
        pagesize: pageSize
      })
    },
    // 获取角色列表
    async getRoles() {
      await this.updateRolesList({
        page: 1,
        pagesize: 10
      })
    },
    // 打开编辑弹出框
    async openEditVisible(rowData) {
      // 记录id
      editingId = rowData.id
      // 打开
      this.editVisible = true
      // 反显
      this.editForm.name = rowData.name
      this.editForm.desc = rowData.description
    },
    // 编辑角色
    async onEdit() {
      await this.updateOneRole(editingId)
      const res = await companySetting.editRole({
        id: editingId,
        description: this.editForm.desc,
        name: this.editForm.name
      })
      this.$message({
        message: res.message,
        type: res.success ? 'success' : 'error'
      })
      if (res.success) {
        this.editVisible = false
        this.getRoles()
      }
    },
    // 打开添加弹出框
    async openAddVisible() {
      this.addVisible = true
    },
    // 添加角色
    async onAdd() {
      const res = await companySetting.addRole({
        name: this.addForm.name,
        description: this.addForm.desc
      })
      this.$message({
        message: res.message,
        type: res.success ? 'success' : 'error'
      })
      if (res.success) {
        this.addVisible = false;
        (this.addForm = {
          name: '',
          desc: ''
        }),
        this.getRoles()
      }
    },
    // 删除角色
    onDelete(id) {
      this.$confirm(
        this.$t('companySetting.okToDelete'),
        this.$t('companySetting.tip'),
        {
          confirmButtonText: this.$t('companySetting.determine'),
          cancelButtonText: this.$t('companySetting.cancel'),
          type: 'warning'
        }
      )
        .then(async() => {
          const res = await companySetting.deleteRole(id)
          this.$message({
            message: res.message,
            type: res.success ? 'success' : 'error'
          })
          if (res.success) {
            // 刷新列表
            this.getRoles()
          }
        })
        .catch(() => {})
    },
    // 打开分配权限对话框 获取所有权限点
    async openPermissionVisible(id) {
      this.permissionVisible = true
      editingId = id
      this.permissionLoading = true,
      // 根据id获取角色权限
      await this.updateOneRole(id)
      this.permissionLoading = false
    },
    // 关闭权限弹窗
    closePermissionDialog() {
      this.permissionVisible = false
    },
    // 根据id分配权限
    async assignPermission() {
      const idList = this.$refs.tree.getCheckedKeys()
      if (idList.length >= 1) {
        const res = await companySetting.assignPermission({
          id: editingId,
          permIds: idList
        })
        this.$message({
          message: res.message,
          type: res.success ? 'success' : 'error'
        })
        if (res.success) {
          this.closePermissionDialog()
        }
      } else {
        this.$message({
          message: this.$t('companySetting.permissionTip'),
          type: 'error'
        })
      }
    },
    async exportExcel() {
      // 数据
      const data = this.rolesList.rows
      const wb = new ExcelJS.Workbook()
      const ws = wb.addWorksheet('表格1')
      ws.columns = this.columns.slice(1, -1).map(col => ({
        header: col.label,
        key: col.prop
      }))
      ws.addRows(data)
      // 文件里的编码
      const buffer = await wb.xlsx.writeBuffer()
      const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
      const blob = new Blob([buffer], { type: EXCEL_TYPE })
      FileSaver.saveAs(blob, '角色列表.xlsx')
    }
  },
  async created() {
    // 获取角色列表
    this.updateRolesList({
      page: this.currentPage,
      pagesize: this.pageSize
    })
    // 获取权限列表
    this.updatePermissionList()
  }
}
</script>
<style lang="scss" scoped>
::v-deep .red {
  background: rgba(0, 0, 0, 0.1);
}
::v-deep .green {
  background: rgba(0, 0, 0, 0.15);
}
::v-deep .yellow {
  background: rgba(0, 0, 0, 0.2);
}
.container {
  padding: 0 16px;
  box-sizing: border-box;
}
</style>
